package com.lpwa.system.service.impl;

import java.util.List;

import com.lpwa.common.exception.BusinessException;
import com.lpwa.common.utils.StringUtils;
import com.lpwa.system.domain.*;
import com.lpwa.system.mapper.LableMapper;
import com.lpwa.system.mapper.LablePersonMapper;
import com.lpwa.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lpwa.system.mapper.PersonMapper;
import com.lpwa.common.core.text.Convert;

/**
 * 人员 服务层实现
 * 
 * @author tanmu
 * @date 2019-05-30
 */
@Service
public class PersonServiceImpl implements IPersonService 
{
	@Autowired
	private PersonMapper personMapper;
	@Autowired
	private LableMapper lableMapper;
	@Autowired
	private LablePersonMapper lablePersonMapper;
	@Autowired
	private IDeviceModelService deviceModelService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ILableService lableService;


	/**
     * 查询人员信息
     * 
     * @param personId 人员ID
     * @return 人员信息
     */
    @Override
	public Person selectPersonById(String personId)
	{
		Person person = personMapper.selectPersonById(personId);
        String lableId = selectbindLableId(personId);
        person.setTagId(lableId);
	    return  person;
	}
	
	/**
     * 查询人员列表
     * 
     * @param person 人员信息
     * @return 人员集合
     */
	@Override
	public List<Person> selectPersonList(Person person)
	{
//        List<Person> personList = personMapper.selectPersonList(person);
//        if (personList.size()>0){
//            for (Person p : personList){
//              List<String> TagList = lablePersonMapper.selectLablePersonListByPersonIds(Convert.toStrArray(p.getPersonId()));
//              if (TagList.size()>0){
//                  p.setTagId(TagList.get(0));
//              }
//            }
//        }
	    return personMapper.selectPersonList(person);
	}
	
    /**
     * 新增人员
     * 
     * @param person 人员信息
     * @return 结果
     */
	@Override
	public int insertPerson(Person person)
	{
		String user = person.getCreateBy();
        person = bindLableId(person,user);
	    return personMapper.insertPerson(person);
	}
	
	/**
     * 修改人员
     * 
     * @param person 人员信息
     * @return 结果
     */
	@Override
	public int updatePerson(Person person)
	{
	    String personId = person.getPersonId();
	    String newLableId = person.getTagId();
        String oldLableId = selectbindLableId(personId);
        String user = person.getUpdateBy();
        if (StringUtils.isEmpty(oldLableId)){//人员未绑定过标签，逻辑同新增
            person = bindLableId(person,user);
        }else if (!newLableId.equals(oldLableId)){//标签解绑并重新绑定，逻辑同新增最后解绑oldLableId
            person = bindLableId(person,user);
            //解绑oldLableID，关系表状态改为未绑定，保留人员与标签关系旧数据
            TagPerson lablePerson = new TagPerson();
            lablePerson.setIsBind("0");
            lablePerson.setTagId(oldLableId);
            lablePerson.setPersonId(personId);
            lablePersonMapper.updateLablePersonByLableId(lablePerson);
            //旧标签的绑定状态也改为未绑定
            Tag lab = new Tag();
            lab.setTagId(oldLableId);
            lab.setIsBind(0);
            lab.setPersonId("");//旧标签绑定人员ID设置为空
            lableMapper.updateLable(lab);
        }
	    return personMapper.updatePerson(person);
	}

	/**
     * 删除人员对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deletePersonByIds(String ids)
	{
        //删除人员同时解除标签和人员的关系，同时将人员标签状态改为未绑定状态
        //通过人员Id集合查找绑定的标签Id集合
        List<String> lableIdList = lablePersonMapper.selectLablePersonListByPersonIds(Convert.toStrArray(ids));
        if (lableIdList.size()>0){
            //解除人员绑定状态改为未绑定状态
            for(String lableId : lableIdList){
                Tag lable = new Tag();
                lable.setTagId(lableId);
                lable.setIsBind(0);
                lableMapper.updateLable(lable);
            }
            //更新关系表绑定状态
            lablePersonMapper.deleteLablePersonByPersonId(Convert.toStrArray(ids));
        }
		return personMapper.deletePersonByIds(Convert.toStrArray(ids));
	}

	@Override
	public String selectMaxPersonId() {
		return personMapper.selectMaxPersonId();
	}
    /**
     * 导入人员数据
     *
     * @param personList 人员数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importPerson(List<Person> personList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(personList) || personList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.person.initPassword");
        for (Person person : personList)
        {
            try
            {
                String tagId = person.getTagId();
                if (!StringUtils.isEmpty(tagId)){
                    person.setTagId(tagId.toLowerCase());
                }
                String maxId = selectMaxPersonId();
                //截取字符串，数字加一自增，然后拼接
                String newId =null;
                if(StringUtils.isEmpty(maxId)){
                    newId = "P0001";
                }else {
                    String oldId ="1"+maxId.substring(1);
                    int num = Integer.parseInt(oldId)+1;
                    String newNum = ""+num;
                    newId = "P"+newNum.substring(1);
                }
                person.setPersonId(newId);
                person.setCreateBy(operName);
//                String tagId = person.getTagId();
                String deptName = person.getDeptName();
                //通过deptName查找deptId
                if (!StringUtils.isEmpty(deptName)){
                    SysDept dept = new SysDept();
                    dept.setDeptName(deptName);
                    List<SysDept> deptList = deptService.selectDeptList(dept);
                    if (deptList.size()>0){
                        person.setDeptId(deptList.get(0).getDeptId());
                        this.insertPerson(person);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、人员 " + person.getPersonName() + " 导入成功");
                    }else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、人员 " + person.getPersonName() + " 所属组织不存在");
                    }
                }else{
                    this.insertPerson(person);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、人员 " + person.getPersonName() + " 导入成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、人员 " + person.getPersonName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
//        return null;
    }

    /**
	 * 根据人员Id查询已绑定标签Id
	 *
	 * @String personId 人员信息
	 * @return 结果
	 */
    @Override
	public String selectbindLableId(String personId) {
        TagPerson lablePerson = new TagPerson();
        lablePerson.setPersonId(personId);
        lablePerson.setIsBind("1");
        //查询绑定标签Id
        List<TagPerson> lablePeopleList=lablePersonMapper.selectLablePersonList(lablePerson);
        if (lablePeopleList.size()>0){
            return lablePeopleList.get(0).getTagId();
        }else {
            return null;
        }
	}

    /**
     * 人员和标签之间的绑定逻辑
     *
     * @String lableId 标签ID
	 * @String personId 人员ID
	 * @String greateBy 用户
     * @return 结果true 绑定成功 FALSE绑定失败
     */
    public Person bindLableId(Person person,String user) {
        String lableId = person.getTagId();
        String personId = person.getPersonId();
        if (!StringUtils.isEmpty(lableId)){
            //判断标签Id在标签表中是否存在
            //查询标签表
            Tag lable = lableMapper.selectLableById(lableId);
            if (StringUtils.isNull(lable)){//为空情况
                //新增标签
                Tag newlable = new Tag();
                newlable.setTagId(lableId);
                //根据标签Id判断标签型号
                String modelCode = lableId.substring(8,10);
                DeviceModel model = deviceModelService.selectDeviceModelByCode(modelCode);
                if (StringUtils.isNull(model)){
                    throw new RuntimeException("标签Id没有匹配对应型号");
                }else{
                    newlable.setTagType(model.getModelId().toString());//标签类型
                }
                newlable.setCreateBy(user);
                newlable.setIsBind(1);//将标签的绑定状态改为“已绑定”
                newlable.setPersonId(personId);//设置标签的绑定人员ID
                int bool = lableService.insertLable(newlable);
                //保存标签和人员关系
                TagPerson lablePerson = new TagPerson();
                lablePerson.setTagId(lableId);
                lablePerson.setPersonId(personId);
                lablePerson.setIsBind("1");
                lablePerson.setCreateBy(user);
                lablePersonMapper.insertLablePerson(lablePerson);
                person.setIsBind(1);
            }else {//非空情况，标签已绑定，标签未绑定
                //判断标签是否绑定
                Integer isBind = lable.getIsBind();
                if (isBind==1){//已绑定
                        throw new RuntimeException("该标签已绑定，请先解绑");
                    }else {
                        //保存标签和人员关系
                    TagPerson lablePer = new TagPerson();
                        lablePer.setTagId(lableId);
                        lablePer.setPersonId(personId);
                        lablePer.setIsBind("1");
                        lablePer.setCreateBy(user);
                        lablePersonMapper.insertLablePerson(lablePer);
                        //标签表的绑定状态也改为已绑定
                        Tag lab = new Tag();
                        lab.setTagId(lableId);
                        lab.setIsBind(1);
                       //设置标签的绑定人员ID
                        lab.setPersonId(personId);
                        lableMapper.updateLable(lab);
                        person.setIsBind(1);
                }
            }
        }else{//标签Id为空，说明未绑定，修改状态下说明该人员解绑标签
            person.setIsBind(0);
        }
        return person;
    }



}
